<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>BrowserRouter 原理</title>
    <style>
      #result {
        width: 400px;
        height: 300px;
        border: solid 1px #ddd;
      }
    </style>
  </head>
  <body>
    <a href="/home">Home</a>
    <a href="/about">About</a>
    <hr />
    <div id="result"></div>

    <script>
      //获取 a 元素
      let links = document.querySelectorAll("a");
      let result = document.querySelector("#result");

      //绑定事件
      links.forEach((link) => {
        link.addEventListener("click", function (e) {
          //1. 阻止默认行为
          e.preventDefault();
          //获取当前所点链接的 href
          let href = e.target.href; //得到的 url 是一个完整版的 url
          //2. 修改页面地址栏的 URL
          history.pushState({ id: 100 }, "", href);
          //获取页面 url 的路径
          let { pathname } = location; ///
          //3. 根据 url 的路径, 进行处理
          switch (pathname) {
            case "/home":
              result.innerHTML = "Home Home Home"; // 渲染组件 Home
              break;
            case "/about":
              result.innerHTML = "About About About"; //渲染组件 About
              break;
            default:
              result.innerHTML = "Not Found";
              break;
          }
        });
      });

      //绑定全局事件
      //当历史从栈结构中弹出的时候, 自动触发这个事件
      window.addEventListener("popstate", function () {
        //获取页面 url 的路径
        let { pathname } = location;
        //3. 根据 url 的路径, 进行处理 
        switch (pathname) {
          case "/home":
            result.innerHTML = "Home Home Home"; // 渲染组件 Home
            break;
          case "/about":
            result.innerHTML = "About About About"; //渲染组件 About
            break;
          default:
            result.innerHTML = "Not Found";
            break;
        }
      });
    </script>
  </body>
</html>
